﻿using Grpc.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using UserCenter.Console.Sdk.Models;
using UserCenter.Console.Sdk.Results;

namespace UserCenter.Console.Sdk.Core
{
    static public class Utils
    {
        static public void SetStatus<T>(this BaseResult sdkResult, GrpcRequestResult<T> grpcRequest)
        {
            sdkResult.Success = grpcRequest.Success;
            sdkResult.Message = grpcRequest.Message;
            sdkResult.Code = grpcRequest.Code;
        }

        /// <summary>
        /// 对象转Metadata
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="isIgnoreNull"></param>
        /// <returns></returns>
        public static Metadata Object2Meta(object obj)
        {
            if (obj == null) return null;
            Metadata entries = new Metadata();

            Type t = obj.GetType(); // 获取对象对应的类， 对应的类型

            PropertyInfo[] pi = t.GetProperties(BindingFlags.Public | BindingFlags.Instance); // 获取当前type公共属性

            foreach (PropertyInfo p in pi)
            {
                MethodInfo m = p.GetGetMethod();

                if (m != null && m.IsPublic)
                {
                    var value = m.Invoke(obj, new object[] { });
                    // 进行判NULL处理 
                    if (value != null)
                    {
                        entries.Add(p.Name, value.ToString()); // 向字典添加元素
                    }
                }
            }
            return entries;
        }
    }
}
